package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.swing.StringUIClientPropertyKey;

import java.util.Date;

/**
 * @author 金园
 * @create 2022/5/17
 * @Description
 * @className DtsAdminServiceImpl
 * @packageName com.qf.service.impl
 */
@Service
public class DtsAdminServiceImpl implements DtsAdminService {
    @Autowired
    DtsAdminMapper adminMapper;
    @Override
    public DtsAdmin findByUsername(String username) {
        LambdaQueryWrapper<DtsAdmin> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DtsAdmin::getUsername,username);
        //根据用户名查询用户对象
        DtsAdmin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public IPage<DtsAdmin> queryPage(Integer page, Integer limit, String sort, String order, String username) {
        //创建分页条件参数
        IPage<DtsAdmin> iPage = new Page(page,limit);
         //插件条件查询
        QueryWrapper<DtsAdmin> qw = new QueryWrapper();

        if (!StringUtils.isEmpty(username)){
             qw.like("username",username);
        }
        if (!StringUtils.isEmpty(sort)&&StringUtils.isEmpty(order)){
           qw.orderByDesc(sort);
        }else {
           qw.orderByAsc(sort);
        }

        adminMapper.selectPage(iPage,qw);
        
        return iPage;
    }

    @Override
    public DtsAdmin add(DtsAdmin admin) {
        admin.setUpdateTime(new Date());
        admin.setAddTime(new Date());
        admin.setDeleted(false);//是否逻辑删除

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        String encode = passwordEncoder.encode(admin.getPassword());

        admin.setPassword(encode);
        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public DtsAdmin update(DtsAdmin admin) {
        //是从前端获取的密码
        String password = admin.getPassword();
        //从数据库中获取的密码
        DtsAdmin adminDB = adminMapper.selectById(admin.getId());
        String passwordDb = adminDB.getPassword();
        //比较密码是否一样，不一样则修改
        if(!password.equalsIgnoreCase(passwordDb)){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(admin.getPassword());
            admin.setPassword(encode);
        }
        admin.setUpdateTime(new Date());
        adminMapper.updateById(admin);
        return admin;
    }
}
